package com.duleme.servlet;

import com.duleme.common.EncodeUtils;
import com.duleme.common.JsonUtils;
import com.duleme.dao.BookDao;
import com.duleme.entity.Book;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.util.JAXBSource;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

@WebServlet(urlPatterns = "/data/book")
public class BookDataServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EncodeUtils.setEncoding(req,resp);
        String method=req.getParameter("method");
        if(method.equals("shop")){
            String shopId=req.getParameter("shopId");
            BookDao dao=new BookDao();
            List<Book> list=dao.findBooksByShopId(Integer.parseInt(shopId));
            if (list!=null){
                resp.getWriter().print(JsonUtils.result2Json("1","books",JsonUtils.toJson(list)));
            }else resp.getWriter().print(JsonUtils.result2Json("0"));
        }else if (method.equals("category")){
            String category= URLDecoder.decode(req.getParameter("category"),"utf-8");
            System.out.println(category);
            BookDao dao=new BookDao();
            List<Book> list=dao.findBooksByCategory(category);
            if (list!=null){
                resp.getWriter().print(JsonUtils.result2Json("1","books",JsonUtils.toJson(list)));
            }else resp.getWriter().print(JsonUtils.result2Json("0"));
        }else if (method.equals("bookId")){
            String bookId=req.getParameter("bookId");
            BookDao dao=new BookDao();
            Book book=dao.findBookByBookId(Integer.parseInt(bookId));
            RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("/Goods_Information.jsp");
            req.setAttribute("book",book);
            requestDispatcher.forward(req,resp);
        }else if (method.equals("search")){
            String bookName=req.getParameter("bookName");
            BookDao dao=new BookDao();
            List<Book> list=dao.findBookByName(bookName);
            if (list!=null){
                resp.getWriter().print(JsonUtils.result2Json("1","books",JsonUtils.toJson(list)));
            }else
                resp.getWriter().print(JsonUtils.result2Json("0"));
        }
        else resp.getWriter().print(JsonUtils.result2Json("0"));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
